<template>
  <div>
    <el-form :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()"
      @submit.native.prevent>
      <!-- 搜索框-->
      <el-form-item prop="createDate">
        <el-date-picker v-model="searchForm.createDate" type="daterange" align="right" unlink-panels range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query()" size="small">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" v-for="(chartData,index) in chartList" :key="index" style="position: relative;">
        <div style="position: absolute; top: 20px; left: 30px; color: #3f9eff;">{{chartData.name}}<span style="font-size: 14px;">（点击量：{{chartData.totalNum}}）</span></div>
        <ve-pie :data="chartData" :settings="chartSettings" :legend-visible="false"></ve-pie>
      </el-col>
    </el-row>

    <el-row>
      <el-button-group class="pull-right">
        <el-button v-if="hasPermission('smis:tongji:jfKioskTongjiClick:export')" type="default" size="small" icon="el-icon-download"
          title="导出" @click="exportExcel()"></el-button>
        <el-button type="default" size="small" icon="el-icon-refresh" @click="refreshList">
        </el-button>
      </el-button-group>
    </el-row>
    <el-table :data="dataList" border size="medium" @selection-change="selectionChangeHandle" @sort-change="sortChangeHandle"
      v-loading="loading" class="table">
      <el-table-column prop="name" show-overflow-tooltip label="商户名">
      </el-table-column>
      <el-table-column prop="roomShow" show-overflow-tooltip label="商铺位置">
      </el-table-column>
      <el-table-column prop="count" show-overflow-tooltip label="点击量">
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageNo"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total" background layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>
</template>

<script>
  import moment from 'moment'
  export default {
    data() {
      this.chartSettings = {
        dimension: '商户名',
        metrics: '访问次数',
        label: {
          formatter: '{b}: {@访问次数}'
        }
      }
      return {
        searchForm: {
          createDate: []
        },
        chartList: [],
        // chartData: {
        //   columns: ['商户名', '访问次数'],
        //   rows: [
        //     { '商户名': 'KFC', '访问次数': 1393 },
        //     { '商户名': '羊肉', '访问次数': 3530 },
        //     { '商户名': '东盛', '访问次数': 2923 },
        //     { '商户名': '很久以前', '访问次数': 1723 },
        //     { '商户名': '那家店', '访问次数': 3792 },
        //     { '商户名': '不知道', '访问次数': 4593 }
        //   ]
        // },
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              picker.$emit('pick', [moment(end).subtract(7, 'days'), end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              picker.$emit('pick', [moment(end).subtract(1,'months'), end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              picker.$emit('pick', [moment(end).subtract(3,'months'), end]);
            }
          }, {
            text: '最近半年',
            onClick(picker) {
              const end = new Date();
              picker.$emit('pick', [moment(end).subtract(6,'months'), end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              picker.$emit('pick', [moment(end).subtract(12,'months'), end]);
            }
          }]
        },
        dataList: [],
        pageNo: 1,
        pageSize: 10,
        total: 0,
        orderBy: '',
        dataListSelections: [],
        isSearchCollapse: false,
        isImportCollapse: false,
        loading: false
      }
    },
    activated() {
      var now = (new Date())
      this.searchForm.createDate = [moment(now).subtract(1,'months'), now]
      this.query()
    },
    methods: {
      query() {
        this.queryTypeList()
        this.refreshList()
      },
      // 查询业态前十点击量
      queryTypeList() {
        this.$http({
          url: '/smis/tongji/jfKioskTongji/typeClickList',
          method: 'get',
          params: {
            'startTime': moment(this.searchForm.createDate[0]).format("YYYY-MM-DD")+' 00:00:00',
            'endTime': moment(this.searchForm.createDate[1]).format("YYYY-MM-DD")+' 23:59:59'
          }
        }).then(({ data }) => {
          if (data && data.success) {
            this.chartList = []
            var typeList = data.type || []
            var merchantList = data.list || []
            typeList.forEach((type) => {
              var chartData = {}
              chartData.columns = ['商户名', '访问次数']
              chartData.name = type.name
              chartData.totalNum =  0
              chartData.rows = []
              for(var i=0; i < merchantList.length; i++) {
                if((merchantList[i].merchantsTypeIds||'').indexOf(type.id) !== -1) {
                  chartData.totalNum +=  merchantList[i].count
                  if(chartData.rows.length <= 10) {
                    chartData.rows.push({
                      '商户名': merchantList[i].name,
                      '访问次数': merchantList[i].count
                    })
                  }
                }
              }
              this.chartList.push(chartData)
            })
          }
        })
      },
      // 获取数据列表
      refreshList() {
        this.loading = true
        this.$http({
          url: '/smis/tongji/jfKioskTongji/merchantClickList',
          method: 'get',
          params: {
            'pageNo': this.pageNo,
            'pageSize': this.pageSize,
            'startTime': moment(this.searchForm.createDate[0]).format("YYYY-MM-DD")+' 00:00:00',
            'endTime': moment(this.searchForm.createDate[1]).format("YYYY-MM-DD")+' 23:59:59'
          }
        }).then(({
          data
        }) => {
          if (data && data.success) {
            this.dataList = data.page.list
            this.total = data.page.count
            this.loading = false
          }
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageNo = 1
        this.refreshList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageNo = val
        this.refreshList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },

      // 排序
      sortChangeHandle(obj) {
        if (obj.order === 'ascending') {
          this.orderBy = obj.prop + ' asc'
        } else if (obj.order === 'descending') {
          this.orderBy = obj.prop + ' desc'
        } else {
          this.orderBy = ''
        }
        this.refreshList()
      },
      // 导入成功
      uploadSuccess(res, file) {
        if (res.success) {
          this.$message.success({
            dangerouslyUseHTMLString: true,
            message: res.msg
          })
        } else {
          this.$message.error(res.msg)
        }
      },
      // 下载模板
      downloadTpl() {
        this.$utils.download('/smis/tongji/jfKioskTongjiClick/import/template')
      },
      exportExcel() {
        var startTime = moment(this.searchForm.createDate[0]).format("YYYY-MM-DD")+' 00:00:00'
        var endTime = moment(this.searchForm.createDate[1]).format("YYYY-MM-DD")+' 23:59:59'
        this.$utils.download('/smis/tongji/jfKioskTongji/export?startTime='+startTime+'&endTime='+endTime)
      },
      resetSearch() {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      }
    }
  }
</script>
